package com.tanhua.dubbo.api.mongo;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 圈子互动服务实现类
 */
@DubboService
@Slf4j
public class FriendApiImpl implements FriendApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 成为好友
     *
     * @param friendUserId
     * @param userId
     */
    @Override
    public void addContacts(Long friendUserId, Long userId) {
        //1.查询好友关系是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("friendId").is(friendUserId));
        if(!mongoTemplate.exists(query,Friend.class)){
            commonAddContacts(friendUserId, userId);
        }
        //2.如果不存在关系 成为好友
        Query query2 = new Query();
        query2.addCriteria(Criteria.where("userId").is(friendUserId).and("friendId").is(userId));
        if(!mongoTemplate.exists(query2,Friend.class)){
            commonAddContacts(userId,friendUserId);
        }
    }

    /**
     * 联系人分页列表查询
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<Friend> findPageContacts(Long page, Long pageSize, Long userId) {
        //1查询总记录数
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        long counts = mongoTemplate.count(query, Friend.class);
        //2当前页面数据
        query.limit(pageSize.intValue()).skip((page-1)*pageSize);
        //2.1 date降序
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //3返回PageResult
        return new PageResult<>(page,pageSize,counts,friendList);
    }

    private void commonAddContacts(Long friendUserId, Long userId) {
        Friend friend = new Friend();
        friend.setFriendId(friendUserId);
        friend.setUserId(userId);
        friend.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(friend);
    }


}
